class MySSEClient {
    #msg = ''
    // #source = new EventSource(`http://localhost:3000/typing`);
    #source = new EventSource('/typing');

    constructor(input) {
        this.input = input
        this.#source.onopen = _ => console.log("Connected");
        this.#source.onerror = console.error;
        // this.#source.onmessage = e => this.onMessage(e);
        this.#source.addEventListener('typing', e => this.onTyping(e))
    }

    // 方式1：监听message事件
    onMessage(e) {
        if (e.data === 'end') {
            // 判定end，关闭连接
            source.close()
        }
        this.#msg += e.data
        console.log(this.#msg)
    }

    // 方式2，监听自定义custom事件
    onTyping(e) {
        this.#msg += e.data
        // this.#msg += JSON.parse(e.data).name // 接收json字符串
        this.input.value = this.#msg
        // console.log(this.#msg)
    }
}

// module.exports = {
//     MySSEClientXXX
// }

// new MySSEClient();
